#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/27
# @Author    :Erinyu
# @Email     :yuailing@bbdservice.com
# @File      :IC_Later1MonUpaidLoanBal
# @Software  :PyCharm

'''eof
name:个人近1个月内到期未结清贷款余额
code:IC_Later1MonUpaidLoanBal
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def NaNCheck(str):
    return False if str in null_type_list else True


def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False


def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp, '%Y%m').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


def past1Mon(time):
    time = time.replace('-', '')
    past1ago = datetime.date.today() - datetime.timedelta(days=30)
    past1ago = past1ago.strftime('%Y%m%d')
    return time >= past1ago


# 个人近1个月内到期未结清贷款余额
# "Factor1=基本信息段（PD01A）中到期日期（PD01AR02）在距申请日期1月内
# 且 最新表现信息段（PD01B）中关闭日期（PD01BR01）==“” 的余额（PD01BJ01）
# Factor = sumFactor1
# PDA[1.1] - PD01[0.*] - PD01A[1.1]/PD01B[1.1] - PD01AR02[0.1]/PD01BR01[1.1]/PD01BJ01[1.1]

def IC_Later1MonUpaidLoanBal():
    data = IC_DSJ.get('data')
    factor = []
    # 借贷账户信息 PDA [1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01 [0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                # 基本信息段 PD01A [1.1]
                PD01A = getTable(i, 'PD01A', 1, 0)
                # 最新表现信息段 PD01B [1.1]
                PD01B = getTable(i, 'PD01B', 1, 1)
                if PD01A == [{}] or PD01B == [{}]:
                    factor.append(None)
                elif PD01A == 0:
                    factor.append(0)
                else:
                    # 到期日期 PD01AR02 [0.1] in 12mons
                    PD01AR02 = PD01A[0].get('PD01AR02')
                    # 关闭日期 PD01BR01 [1.1] == ""
                    PD01BR01 = PD01B[0].get('PD01BR01')
                    if Formate(PD01AR02) is None:
                        # 缺失值
                        factor.append(None)
                    else:
                        if PD01BR01 == '' and past1Mon(Formate(PD01AR02)):
                            # 余额 PD01BJ01 [1.1]
                            PD01BJ01 = PD01B[0].get('PD01BJ01')
                            if (NaNCheck(PD01BJ01) and intCheck(PD01BJ01)):
                                # 缺失值
                                factor.append(None)
                            else:
                                factor.append(int(PD01BJ01))
                        else:
                            # 不是缺失值，只是不符合条件
                            factor.append(0)

    factor = [x for x in factor if x is not None]
    return u'缺失值' if len(factor) == 0 else sum(factor)


if __name__ == '__main__':
    file_obj = open(r'IC_DSJ.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False)
    IC_DSJ = IC_DSJ.get('IC_DSJ')
    res = IC_Later1MonUpaidLoanBal()
    print(res)

result = IC_Later1MonUpaidLoanBal()